package middleware

import (
	"github.com/gin-gonic/gin"
	"shop/model"
	"shop/pkg/constant"
	"shop/pkg/err"
	"shop/pkg/utils"
)

// JWTHandler 解析token并放入context
func JWTHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		token := context.Request.Header.Get("token")
		if token == "" {
			panic(err.ApiError{ErrorCode: constant.ErrTokenExpire})
		}
		user := utils.ParseToken(token)
		if user == (model.User{}) {
			panic(err.ApiError{ErrorCode: constant.ErrTokenExpire})
		} else {
			context.Set("userName", user.Username)
			context.Set("userId", user.ID)
			context.Next()
		}
	}
}
